class Admin::StatisticalDatumController < ApplicationController
  layout "admin"
  before_action :month_begin_at
  #设置财务数据权限验证
  before_action :authorize_finance, only: [:finance]
  #设置导师数据权限验证
  before_action :authorize_teacher, only: [:teacher]
  #设置课程数据权限验证
  before_action :authorize_curriculum, only: [:curriculum]

  #综合统计
  def comprehensive
    company = current_company
    @studios = company.studios
    params[:studio_id] ||= "all"
    @student_count = company.students.count
    @potential_student_count = company.potential_students.where(status: "未转化").count
    @expire = company.students.select {|stu| stu unless stu.is_expire}.size
    @finance_income = company.finances.where(finance_type: "收入").sum("amount")
    @finance_expend = company.finances.where(finance_type: "支出").sum("amount")
    @course_reckons = company.course_reckons.sum("amount")
    ########顶部结束###########
    if params[:studio_id] == "all"
      @studio_name = "所有分店"     
      #市场专员招生进度进度条展示
      @student_progress = company.students.where(created_at: (@month_begin_at)..(Date.current)).count
      @market_target = company.studios.map { |stu| stu.targets_of_month(@month_begin_at.to_s, "市场总监").to_i }.inject(0) { |sum, element| sum + element }  
      @market_width = "0"
      if @student_progress.to_f > @market_target.to_f
        @market_width = "100"
      else
        if @market_target == 0
          @market_width = "0"
        else
          @market_width = "#{(100*@student_progress.to_f/@market_target.to_f).round(2)}"
        end
      end
      ########招生结束###########
      #服务顾问服务进度进度条展示
      @students_expent = company.orders.where(created_at: (@month_begin_at)..(Date.current)).sum(:total_price) 
      @service_target = company.studios.map { |stu| stu.targets_of_month(@month_begin_at.to_s, "运营总监").to_i }.inject(0) { |sum, element| sum + element }  
      @service_width = "0"
      if @students_expent.to_f > @service_target.to_f
        @service_width = "100"
      else
        if @service_target == 0
          @service_width = "0"
        else
          @service_width = "#{(100*@students_expent.to_f/@service_target.to_f).round(2)}"
        end
      end
      ########服务结束###########
      ###导师课消进度进度条展示##
      @students_reckon = company.course_reckons.where(reckon_at: (@month_begin_at)..(Date.current)).sum(:amount) 
      @teacher_target = company.studios.map { |stu| stu.targets_of_month(@month_begin_at.to_s, "产品总监").to_i }.inject(0) { |sum, element| sum + element }   
      @reckon_width = "0"
      if @students_reckon.to_f > @teacher_target.to_f
        @reckon_width = "100"
      else
        if @teacher_target == 0
          @reckon_width = "0"
        else
          @reckon_width = "#{(100*@students_reckon.to_f/@teacher_target.to_f).round(2)}"
        end
      end
      ########课消结束###########
    else
      studio = Studio.find(params[:studio_id])
      @studio_name = studio.name   
      @student_progress = studio.students.where(created_at: (@month_begin_at)..(Date.current)).count
      @market_target = studio.targets_of_month(@month_begin_at.to_s, "市场总监").to_i 
      @market_width = "0"
      if @student_progress.to_f > @market_target.to_f
        @market_width = "100"
      else
        if @market_target == 0
          @market_width = "0"
        else
          @market_width = "#{(100*@student_progress.to_f/@market_target.to_f).round(2)}"
        end
      end
      ########招生结束###########
      #服务顾问服务进度进度条展示
      @students_expent = Order.joins(student: [:studio]).where("studios.id = #{studio.id}").where(created_at: (@month_begin_at)..(Date.current)).sum(:total_price) 
      @service_target = studio.targets_of_month(@month_begin_at.to_s, "运营总监").to_i 
      @service_width = "0"
      if @students_expent.to_f > @service_target.to_f
        @service_width = "100"
      else
        if @service_target == 0
          @service_width = "0"
        else
          @service_width = "#{(100*@students_expent.to_f/@service_target.to_f).round(2)}"
        end
      end
      ########服务结束###########
      ###导师课消进度进度条展示##
      @students_reckon = CourseReckon.where("studio_id = #{studio.id}").where(reckon_at: (@month_begin_at)..(Date.current)).sum(:amount) 
      @teacher_target = studio.targets_of_month(@month_begin_at.to_s, "产品总监").to_i 
      @reckon_width = "0"
      if @students_reckon.to_f > @teacher_target.to_f
        @reckon_width = "100"
      else
        if @teacher_target == 0
          @reckon_width = "0"
        else
          @reckon_width = "#{(100*@students_reckon.to_f/@teacher_target.to_f).round(2)}"
        end
      end
    end
  end

  def change_comprehensive
    company = current_company
    @studios = company.studios
    params[:studio_id] ||= "all"

    ########顶部结束###########
    if params[:studio_id] == "all"
      @studio_name = "所有分店"          
      #市场专员招生进度进度条展示
      @student_progress = company.students.where(created_at: (@month_begin_at)..(Date.current)).count
      @market_target = company.studios.map { |stu| stu.targets_of_month(@month_begin_at.to_s, "市场总监").to_i }.inject(0) { |sum, element| sum + element }  
      @market_width = "0"
      if @student_progress.to_f > @market_target.to_f
        @market_width = "100"
      else
        if @market_target == 0
          @market_width = "0"
        else
          @market_width = "#{(100*@student_progress.to_f/@market_target.to_f).round(2)}"
        end
      end
      ########招生结束###########
      #服务顾问服务进度进度条展示
      @students_expent = company.orders.where(created_at: (@month_begin_at)..(Date.current)).sum(:total_price) 
      @service_target = company.studios.map { |stu| stu.targets_of_month(@month_begin_at.to_s, "运营总监").to_i }.inject(0) { |sum, element| sum + element }  
      @service_width = "0"
      if @students_expent.to_f > @service_target.to_f
        @service_width = "100"
      else
        if @service_target == 0
          @service_width = "0"
        else
          @service_width = "#{(100*@students_expent.to_f/@service_target.to_f).round(2)}"
        end
      end
      ########服务结束###########
      ###导师课消进度进度条展示##
      @students_reckon = company.course_reckons.where(reckon_at: (@month_begin_at)..(Date.current)).sum(:amount) 
      @teacher_target = company.studios.map { |stu| stu.targets_of_month(@month_begin_at.to_s, "产品总监").to_i }.inject(0) { |sum, element| sum + element }   
      @reckon_width = "0"
      if @students_reckon.to_f > @teacher_target.to_f
        @reckon_width = "100"
      else
        if @teacher_target == 0
          @reckon_width = "0"
        else
          @reckon_width = "#{(100*@students_reckon.to_f/@teacher_target.to_f).round(2)}"
        end
      end
      ########课消结束###########
    else
      studio = Studio.find(params[:studio_id])
      @studio_name = studio.name   
      @student_progress = studio.students.where(created_at: (@month_begin_at)..(Date.current)).count
      @market_target = studio.targets_of_month(@month_begin_at.to_s, "市场总监").to_i 
      @market_width = "0"
      if @student_progress.to_f > @market_target.to_f
        @market_width = "100"
      else
        if @market_target == 0
          @market_width = "0"
        else
          @market_width = "#{(100*@student_progress.to_f/@market_target.to_f).round(2)}"
        end
      end
      ########招生结束###########
      #服务顾问服务进度进度条展示
      @students_expent = Order.joins(student: [:studio]).where("studios.id = #{studio.id}").where(created_at: (@month_begin_at)..(Date.current)).sum(:total_price) 
      @service_target = studio.targets_of_month(@month_begin_at.to_s, "运营总监").to_i 
      @service_width = "0"
      if @students_expent.to_f > @service_target.to_f
        @service_width = "100"
      else
        if @service_target == 0
          @service_width = "0"
        else
          @service_width = "#{(100*@students_expent.to_f/@service_target.to_f).round(2)}"
        end
      end
      ########服务结束###########
      ###导师课消进度进度条展示##
      @students_reckon = CourseReckon.where("studio_id = #{studio.id}").where(reckon_at: (@month_begin_at)..(Date.current)).sum(:amount) 
      @teacher_target = studio.targets_of_month(@month_begin_at.to_s, "产品总监").to_i 
      @reckon_width = "0"
      if @students_reckon.to_f > @teacher_target.to_f
        @reckon_width = "100"
      else
        if @teacher_target == 0
          @reckon_width = "0"
        else
          @reckon_width = "#{(100*@students_reckon.to_f/@teacher_target.to_f).round(2)}"
        end
      end
    end
  end

  #学生信息
  def student
    company = current_company
    @studios = company.studios
    #studio = current_studio
    #=======最近30天数据=======#
    #时间数组
    @student_date_array = []
    #新增学员数组
    @grow_students = []
    #学员消费数组
    @spend_students = []
    for day in ((Date.current - 30.day)..Date.current)
      nowday = day.strftime('%Y-%m-%d')
      @student_date_array.push(nowday)
      day_students = company.students.where("students.created_at like '%#{day}%'").count
      @grow_students.push(day_students)
      day_spend = company.orders.where("orders.created_at like '%#{day}%'").select("student_id").distinct.count
      @spend_students.push(day_spend)
    end
    #===========================#
    #==========所有学员课消类型比例==========#
    @reckon_pay_way_key = []
    @reckon_pay_way_value = []
    @course_reckons = company.course_reckons
    @course_reckons_group = @course_reckons.group_by {|s| s.pay_way}
    @course_reckons_group.each do |key, reckon|
      @reckon_pay_way_key.push(key) 
      ps_hash = {value: reckon.size, name: "#{key}"}
      @reckon_pay_way_value.push(ps_hash)
    end
    @reckon_pay_way_value = @reckon_pay_way_value.to_json 
    @reckon_pay_way_key = @reckon_pay_way_key.to_json 
    #===========================#
    #==========所有学员性别比例==========#
    @all_student_sex_array = []
    students_group = company.students.group_by {|s| s.sex}
    students_group.each do |key, stus|
      ps_hash = {value: stus.size, name: "#{key}"}
      @all_student_sex_array.push(ps_hash)
    end
    @all_student_sex_array = @all_student_sex_array.to_json 
    p @all_student_sex_array
    #===========================#
     ##学员年龄分组
    @student_age_group_arr = []
    #幼儿
    child_count = company.students.where("birthday between '#{Date.current - 6.year}' and '#{Date.current - 3.year}'").count
    ps_hash = {value: child_count, name: "幼儿"}
    @student_age_group_arr.push(ps_hash)
    #少年
    youngster_count = company.students.where("birthday between '#{Date.current - 12.year}' and '#{Date.current - 6.year}'").count
    ps_hash = {value: youngster_count, name: "少年"}
    @student_age_group_arr.push(ps_hash)
    #青少年
    youth_count = company.students.where("birthday between '#{Date.current - 18.year}' and '#{Date.current - 12.year}'").count
    ps_hash = {value: youth_count, name: "青少年"}
    @student_age_group_arr.push(ps_hash)
    #成年
    adult_count = company.students.where("birthday < '#{Date.current - 18.year}'").count
    ps_hash = {value: adult_count, name: "成年"}
    @student_age_group_arr.push(ps_hash)
    @student_age_group_arr = @student_age_group_arr.to_json
    #===========================#
    #学员消费能力分组
    @student_shopping_level = []
    #0-5k
    k0_5 = company.students.where("accumulated_amount between 0 and 4999").count
    k0_5 = {value: k0_5, name: "0-5k"}
    @student_shopping_level.push(k0_5)
    #5-10k
    k5_10 = company.students.where("accumulated_amount between 5000 and 9999").count
    k5_10 = {value: k5_10, name: "5-10k"}
    @student_shopping_level.push(k5_10)
    #10-20k
    k10_20 = company.students.where("accumulated_amount between 10000 and 19999").count
    k10_20 = {value: k10_20, name: "10k-20k"}
    @student_shopping_level.push(k10_20)
    #20+k
    k20 = company.students.where("accumulated_amount > 20000").count    
    k20 = {value: k20, name: "20k以上"}
    @student_shopping_level.push(k20)
    @student_shopping_level = @student_shopping_level.to_json
    
  end

  def change_student
    company = current_company
    params[:studio_id] ||= "all"

    #=======最近30天数据=======#
    #时间数组
    @student_date_array = []
    #新增学员数组
    @grow_students = []
    #学员消费数组
    @spend_students = []
    if params[:studio_id] == "all"
      for day in ((Date.current - 30.day)..Date.current)
        nowday = day.strftime('%Y-%m-%d')
        @student_date_array.push(nowday)
        day_students = company.students.where("students.created_at like '%#{day}%'").count
        @grow_students.push(day_students)
        day_spend = company.orders.where("orders.created_at like '%#{day}%'").select("student_id").distinct.count
        @spend_students.push(day_spend)
      end
      #==========所有学员课消类型比例==========#
      @reckon_pay_way_key = []
      @reckon_pay_way_value = []
      @course_reckons = company.course_reckons
      @course_reckons_group = @course_reckons.group_by {|s| s.pay_way}
      @course_reckons_group.each do |key, reckon|
        @reckon_pay_way_key.push(key) 
        ps_hash = {value: reckon.size, name: "#{key}"}
        @reckon_pay_way_value.push(ps_hash)
      end
      @reckon_pay_way_value = @reckon_pay_way_value.to_json 
      @reckon_pay_way_key = @reckon_pay_way_key.to_json 
      #===========================#
      #==========所有学员性别比例==========#
      @all_student_sex_array = []
      students_group = company.students.group_by {|s| s.sex}
      students_group.each do |key, stus|
        ps_hash = {value: stus.size, name: "#{key}"}
        @all_student_sex_array.push(ps_hash)
      end
      @all_student_sex_array = @all_student_sex_array.to_json 
      p @all_student_sex_array
      #===========================#
       ##学员年龄分组
      @student_age_group_arr = []
      #幼儿
      child_count = company.students.where("birthday between '#{Date.current - 6.year}' and '#{Date.current - 3.year}'").count
      ps_hash = {value: child_count, name: "幼儿"}
      @student_age_group_arr.push(ps_hash)
      #少年
      youngster_count = company.students.where("birthday between '#{Date.current - 12.year}' and '#{Date.current - 6.year}'").count
      ps_hash = {value: youngster_count, name: "少年"}
      @student_age_group_arr.push(ps_hash)
      #青少年
      youth_count = company.students.where("birthday between '#{Date.current - 18.year}' and '#{Date.current - 12.year}'").count
      ps_hash = {value: youth_count, name: "青少年"}
      @student_age_group_arr.push(ps_hash)
      #成年
      adult_count = company.students.where("birthday < '#{Date.current - 18.year}'").count
      ps_hash = {value: adult_count, name: "成年"}
      @student_age_group_arr.push(ps_hash)
      @student_age_group_arr = @student_age_group_arr.to_json
      #===========================#
      #学员消费能力分组
      @student_shopping_level = []
      #0-5k
      k0_5 = company.students.where("accumulated_amount between 0 and 4999").count
      k0_5 = {value: k0_5, name: "0-5k"}
      @student_shopping_level.push(k0_5)
      #5-10k
      k5_10 = company.students.where("accumulated_amount between 5000 and 9999").count
      k5_10 = {value: k5_10, name: "5-10k"}
      @student_shopping_level.push(k5_10)
      #10-20k
      k10_20 = company.students.where("accumulated_amount between 10000 and 19999").count
      k10_20 = {value: k10_20, name: "10k-20k"}
      @student_shopping_level.push(k10_20)
      #20+k
      k20 = company.students.where("accumulated_amount > 20000").count    
      k20 = {value: k20, name: "20k以上"}
      @student_shopping_level.push(k20)
      @student_shopping_level = @student_shopping_level.to_json
    else
      studio = Studio.find(params[:studio_id])
      for day in ((Date.current - 30.day)..Date.current)
        nowday = day.strftime('%Y-%m-%d')
        @student_date_array.push(nowday)
        day_students = studio.students.where("students.created_at like '%#{day}%'").count
        @grow_students.push(day_students)
        day_spend = studio.student_orders.where("orders.created_at like '%#{day}%'").select("student_id").distinct.count
        @spend_students.push(day_spend)
      end
       #==========所有学员课消类型比例==========#
      @reckon_pay_way_key = []
      @reckon_pay_way_value = []
      @course_reckons = studio.course_reckons
      @course_reckons_group = @course_reckons.group_by {|s| s.pay_way}
      @course_reckons_group.each do |key, reckon|
        @reckon_pay_way_key.push(key) 
        ps_hash = {value: reckon.size, name: "#{key}"}
        @reckon_pay_way_value.push(ps_hash)
      end
      @reckon_pay_way_value = @reckon_pay_way_value.to_json 
      @reckon_pay_way_key = @reckon_pay_way_key.to_json 
      #===========================#
      #==========所有学员性别比例==========#
      @all_student_sex_array = []
      students_group = studio.students.group_by {|s| s.sex}
      students_group.each do |key, stus|
        ps_hash = {value: stus.size, name: "#{key}"}
        @all_student_sex_array.push(ps_hash)
      end
      @all_student_sex_array = @all_student_sex_array.to_json 
      p @all_student_sex_array
      #===========================#
       ##学员年龄分组
      @student_age_group_arr = []
      #幼儿
      child_count = studio.students.where("birthday between '#{Date.current - 6.year}' and '#{Date.current - 3.year}'").count
      ps_hash = {value: child_count, name: "幼儿"}
      @student_age_group_arr.push(ps_hash)
      #少年
      youngster_count = studio.students.where("birthday between '#{Date.current - 12.year}' and '#{Date.current - 6.year}'").count
      ps_hash = {value: youngster_count, name: "少年"}
      @student_age_group_arr.push(ps_hash)
      #青少年
      youth_count = studio.students.where("birthday between '#{Date.current - 18.year}' and '#{Date.current - 12.year}'").count
      ps_hash = {value: youth_count, name: "青少年"}
      @student_age_group_arr.push(ps_hash)
      #成年
      adult_count = studio.students.where("birthday < '#{Date.current - 18.year}'").count
      ps_hash = {value: adult_count, name: "成年"}
      @student_age_group_arr.push(ps_hash)
      @student_age_group_arr = @student_age_group_arr.to_json
      #===========================#
      #学员消费能力分组
      @student_shopping_level = []
      #0-5k
      k0_5 = studio.students.where("accumulated_amount between 0 and 4999").count
      k0_5 = {value: k0_5, name: "0-5k"}
      @student_shopping_level.push(k0_5)
      #5-10k
      k5_10 = studio.students.where("accumulated_amount between 5000 and 9999").count
      k5_10 = {value: k5_10, name: "5-10k"}
      @student_shopping_level.push(k5_10)
      #10-20k
      k10_20 = studio.students.where("accumulated_amount between 10000 and 19999").count
      k10_20 = {value: k10_20, name: "10k-20k"}
      @student_shopping_level.push(k10_20)
      #20+k
      k20 = studio.students.where("accumulated_amount > 20000").count    
      k20 = {value: k20, name: "20k以上"}
      @student_shopping_level.push(k20)
      @student_shopping_level = @student_shopping_level.to_json
    end
  end

  #导师统计,kevin
  def teacher
    company = current_company;
    @studios = company.studios;

    @course_teacher_name_array = Array.new(10, "未知");
    @course_teacher_amount_array = Array.new(10, 0); 
    # 导师课消金额排行
    course_teacher_rank = CourseReckon.select("sum(course_reckons.amount) as amount, teacher_id")
        .where(studio_id: @studios.ids)
        .where("course_reckons.created_at between '#{Time.new(@month_begin_at.to_s).strftime("%Y-%m-%d %H:%M:%S")}' and '#{Time.new.strftime("%Y-%m-%d %H:%M:%S")}'")
        .group("course_reckons.teacher_id")
        .order("sum(course_reckons.amount) asc")
        .limit(10);
    for rank in course_teacher_rank
        @course_teacher_name_array.push(rank.teacher.name);
        @course_teacher_amount_array.push(rank.amount.to_f);
    end
    @course_teacher_name_array = @course_teacher_name_array[-10,10];
    @course_teacher_amount_array = @course_teacher_amount_array[-10,10];
  end

  def change_teacher
    company = current_company;
    @studios = company.studios;
    
    @course_teacher_name_array = Array.new(10, "未知");
    @course_teacher_amount_array = Array.new(10, 0); 
    # 导师课消金额排行
    course_teacher_rank = nil;
    if  params[:studio_id] == "all"
      course_teacher_rank = CourseReckon.select("sum(course_reckons.amount) as amount, teacher_id")
        .where(studio_id: @studios.ids)
        .where("course_reckons.created_at between '#{Time.new(@month_begin_at.to_s).strftime("%Y-%m-%d %H:%M:%S")}' and '#{Time.new.strftime("%Y-%m-%d %H:%M:%S")}'")
        .group("course_reckons.teacher_id")
        .order("sum(course_reckons.amount) asc")
        .limit(10);
    else
      course_teacher_rank = CourseReckon.select("sum(course_reckons.amount) as amount, teacher_id")
        .where(studio_id: params[:studio_id])
        .where("course_reckons.created_at between '#{Time.new(@month_begin_at.to_s).strftime("%Y-%m-%d %H:%M:%S")}' and '#{Time.new.strftime("%Y-%m-%d %H:%M:%S")}'")
        .group("course_reckons.teacher_id")
        .order("sum(course_reckons.amount) asc")
        .limit(10);
    end
    
    for rank in course_teacher_rank
        @course_teacher_name_array.push(rank.teacher.name);
        @course_teacher_amount_array.push(rank.amount.to_f);
    end
    @course_teacher_name_array = @course_teacher_name_array[-10,10];
    @course_teacher_amount_array = @course_teacher_amount_array[-10,10];
  end


  #课程数据,kevin
  def curriculum
    company = current_company
    @studios = company.studios
    #=======本月课消排行前十========#
    #课程名字集合
    @course_name_range_arr = Array.new(10, "未知") 
    #上课次数集合
    @course_reckons_range_arr = Array.new(10, 0) 
    reckons = company.course_reckons.joins(:course_info).select("course_infos.name as course_name, count(course_reckons.course_info_id) as reckon_amount").where("course_reckons.created_at between '#{Time.new(@month_begin_at.to_s).strftime("%Y-%m-%d %H:%M:%S")}'and '#{Time.new.strftime("%Y-%m-%d %H:%M:%S")}'").group("course_reckons.course_info_id").order("count(course_reckons.course_info_id) desc").limit(10)
    reckons = reckons.reverse;
    reckons.each do |re|
      @course_name_range_arr.push(re.course_name)
      @course_reckons_range_arr.push(re.reckon_amount) 
    end
    @course_name_range_arr = @course_name_range_arr[-10,10]
    @course_reckons_range_arr = @course_reckons_range_arr[-10,10]
    #============================
    #本月教室使用排行
    @room_course_reckons_arr = []
    room_course_reckons = company.course_reckons.joins(course_info: :room).select("course_room_configurations.room_name as room_name, count(course_reckons.course_info_id) as reckon_amount").where("course_reckons.created_at between '#{Time.new(@month_begin_at.to_s).strftime("%Y-%m-%d %H:%M:%S")}'and '#{Time.new.strftime("%Y-%m-%d %H:%M:%S")}'").group("course_reckons.course_info_id").order("count(course_reckons.course_info_id) desc").limit(10)
    room_course_reckons.each do |room_course| 
      rc = {value: room_course.reckon_amount, name: "#{room_course.room_name}"}
      @room_course_reckons_arr.push(rc)
    end
    @room_course_reckons_arr = @room_course_reckons_arr.to_json
    #============================
    #本月课程消费类型
    @sale_type_course_reckons_arr = []
    sale_type_course_reckons = company.course_reckons.joins(:course_info).select("course_infos.sale_type as sale_name, count(course_reckons.course_info_id) as reckon_amount").where("course_reckons.created_at between '#{Time.new(@month_begin_at.to_s).strftime("%Y-%m-%d %H:%M:%S")}'and '#{Time.new.strftime("%Y-%m-%d %H:%M:%S")}'").group("course_infos.sale_type").order("count(course_reckons.course_info_id) desc").limit(10)
    sale_type_course_reckons.each do |sale_course| 
      sc = {value: sale_course.reckon_amount, name: "#{sale_course.sale_name}"}
      @sale_type_course_reckons_arr.push(sc)
    end
    @sale_type_course_reckons_arr = @sale_type_course_reckons_arr.to_json
    #============================
    #本月课程类型类型
    @course_type_course_reckons_arr = []
    course_type_course_reckons = company.course_reckons.joins(:course_info).select("course_infos.course_type as type_name, count(course_reckons.course_info_id) as reckon_amount").where("course_reckons.created_at between '#{Time.new(@month_begin_at.to_s).strftime("%Y-%m-%d %H:%M:%S")}'and '#{Time.new.strftime("%Y-%m-%d %H:%M:%S")}'").group("course_infos.course_type").order("count(course_reckons.course_info_id) desc").limit(10)
    course_type_course_reckons.each do |type_course| 
      tc = {value: type_course.reckon_amount, name: "#{type_course.type_name}"}
      @course_type_course_reckons_arr.push(tc)
    end
    @course_type_course_reckons_arr = @course_type_course_reckons_arr.to_json
    #============================
    #本月课程支付类型
    @pay_way_course_reckons_arr = []
    pay_way_course_reckons = company.course_reckons.select("course_reckons.pay_way , count(course_reckons.pay_way) as reckon_amount").where("course_reckons.created_at between '#{Time.new(@month_begin_at.to_s).strftime("%Y-%m-%d %H:%M:%S")}'and '#{Time.new.strftime("%Y-%m-%d %H:%M:%S")}'").group("course_reckons.pay_way").order("count(course_reckons.pay_way) desc").limit(10)
    pay_way_course_reckons.each do |pay_course| 
      pc = {value: pay_course.reckon_amount, name: "#{pay_course.pay_way}"}
      @pay_way_course_reckons_arr.push(pc)
    end
    @pay_way_course_reckons_arr = @pay_way_course_reckons_arr.to_json
    
  end

  def change_curriculum
    company = current_company
    params[:studio_id] ||= "all"
    if params[:studio_id] == "all"
      reckons = company.course_reckons.joins(:course_info).select("course_infos.name as course_name, count(course_reckons.course_info_id) as reckon_amount").where("course_reckons.created_at between '#{Time.new(@month_begin_at.to_s).strftime("%Y-%m-%d %H:%M:%S")}'and '#{Time.new.strftime("%Y-%m-%d %H:%M:%S")}'").group("course_reckons.course_info_id").order("count(course_reckons.course_info_id) desc").limit(10)
      room_course_reckons = company.course_reckons.joins(course_info: :room).select("course_room_configurations.room_name as room_name, count(course_reckons.course_info_id) as reckon_amount").where("course_reckons.created_at between '#{Time.new(@month_begin_at.to_s).strftime("%Y-%m-%d %H:%M:%S")}'and '#{Time.new.strftime("%Y-%m-%d %H:%M:%S")}'").group("course_reckons.course_info_id").order("count(course_reckons.course_info_id) desc").limit(10)
      sale_type_course_reckons = company.course_reckons.joins(:course_info).select("course_infos.sale_type as sale_name, count(course_reckons.course_info_id) as reckon_amount").where("course_reckons.created_at between '#{Time.new(@month_begin_at.to_s).strftime("%Y-%m-%d %H:%M:%S")}'and '#{Time.new.strftime("%Y-%m-%d %H:%M:%S")}'").group("course_infos.sale_type").order("count(course_reckons.course_info_id) desc").limit(10)
      course_type_course_reckons = company.course_reckons.joins(:course_info).select("course_infos.course_type as type_name, count(course_reckons.course_info_id) as reckon_amount").where("course_reckons.created_at between '#{Time.new(@month_begin_at.to_s).strftime("%Y-%m-%d %H:%M:%S")}'and '#{Time.new.strftime("%Y-%m-%d %H:%M:%S")}'").group("course_infos.course_type").order("count(course_reckons.course_info_id) desc").limit(10)
      pay_way_course_reckons = company.course_reckons.select("course_reckons.pay_way , count(course_reckons.pay_way) as reckon_amount").where("course_reckons.created_at between '#{Time.new(@month_begin_at.to_s).strftime("%Y-%m-%d %H:%M:%S")}'and '#{Time.new.strftime("%Y-%m-%d %H:%M:%S")}'").group("course_reckons.pay_way").order("count(course_reckons.pay_way) desc").limit(10)
    else
      studio = Studio.find(params[:studio_id])
      reckons = studio.course_reckons.joins(:course_info).select("course_infos.name as course_name, count(course_reckons.course_info_id) as reckon_amount").where("course_reckons.created_at between '#{Time.new(@month_begin_at.to_s).strftime("%Y-%m-%d %H:%M:%S")}'and '#{Time.new.strftime("%Y-%m-%d %H:%M:%S")}'").group("course_reckons.course_info_id").order("count(course_reckons.course_info_id) desc").limit(10)
      room_course_reckons = studio.course_reckons.joins(course_info: :room).select("course_room_configurations.room_name as room_name, count(course_reckons.course_info_id) as reckon_amount").where("course_reckons.created_at between '#{Time.new(@month_begin_at.to_s).strftime("%Y-%m-%d %H:%M:%S")}'and '#{Time.new.strftime("%Y-%m-%d %H:%M:%S")}'").group("course_reckons.course_info_id").order("count(course_reckons.course_info_id) desc").limit(10)
      sale_type_course_reckons = studio.course_reckons.joins(:course_info).select("course_infos.sale_type as sale_name, count(course_reckons.course_info_id) as reckon_amount").where("course_reckons.created_at between '#{Time.new(@month_begin_at.to_s).strftime("%Y-%m-%d %H:%M:%S")}'and '#{Time.new.strftime("%Y-%m-%d %H:%M:%S")}'").group("course_infos.sale_type").order("count(course_reckons.course_info_id) desc").limit(10)
      course_type_course_reckons = studio.course_reckons.joins(:course_info).select("course_infos.course_type as type_name, count(course_reckons.course_info_id) as reckon_amount").where("course_reckons.created_at between '#{Time.new(@month_begin_at.to_s).strftime("%Y-%m-%d %H:%M:%S")}'and '#{Time.new.strftime("%Y-%m-%d %H:%M:%S")}'").group("course_infos.course_type").order("count(course_reckons.course_info_id) desc").limit(10)
      pay_way_course_reckons = studio.course_reckons.select("course_reckons.pay_way , count(course_reckons.pay_way) as reckon_amount").where("course_reckons.created_at between '#{Time.new(@month_begin_at.to_s).strftime("%Y-%m-%d %H:%M:%S")}'and '#{Time.new.strftime("%Y-%m-%d %H:%M:%S")}'").group("course_reckons.pay_way").order("count(course_reckons.pay_way) desc").limit(10)
    end
    #studio = current_studio
    #=======本月课消排行前十========#
    #课程名字集合
    @course_name_range_arr = Array.new(10, "未知") 
    #上课次数集合
    @course_reckons_range_arr = Array.new(10, 0);
    reckons = reckons.reverse;
    reckons.each do |re|
      @course_name_range_arr.push(re.course_name)
      @course_reckons_range_arr.push(re.reckon_amount) 
    end
    @course_name_range_arr = @course_name_range_arr[-10,10]
    @course_reckons_range_arr = @course_reckons_range_arr[-10,10]
    #============================
    #本月教室使用排行
    @room_course_reckons_arr = []
    room_course_reckons.each do |room_course| 
      rc = {value: room_course.reckon_amount, name: "#{room_course.room_name}"}
      @room_course_reckons_arr.push(rc)
    end
    @room_course_reckons_arr = @room_course_reckons_arr.to_json
    #============================
    #本月课程消费类型
    @sale_type_course_reckons_arr = []
    sale_type_course_reckons.each do |sale_course| 
      sc = {value: sale_course.reckon_amount, name: "#{sale_course.sale_name}"}
      @sale_type_course_reckons_arr.push(sc)
    end
    @sale_type_course_reckons_arr = @sale_type_course_reckons_arr.to_json
    #============================
    #本月课程类型类型
    @course_type_course_reckons_arr = []
    course_type_course_reckons.each do |type_course| 
      tc = {value: type_course.reckon_amount, name: "#{type_course.type_name}"}
      @course_type_course_reckons_arr.push(tc)
    end
    @course_type_course_reckons_arr = @course_type_course_reckons_arr.to_json
    #============================
    #本月课程支付类型
    @pay_way_course_reckons_arr = []
    pay_way_course_reckons.each do |pay_course| 
      pc = {value: pay_course.reckon_amount, name: "#{pay_course.pay_way}"}
      @pay_way_course_reckons_arr.push(pc)
    end
    @pay_way_course_reckons_arr = @pay_way_course_reckons_arr.to_json
  end


  #商品数据,kevin,过去三十天数据
  def commodity
    p company = current_company;
    p @studios = company.studios;

    start = Time.now;

    ################################30天之前总计################################
    # 累积营业额(元)
    @total_price = 0;
    # 课程商品金额
    good_ids = Good.where(good_type: "课程商品").ids;
    @total_price_lesson = 0;
    # 周边商品金额
    @total_price_peripheral = 0;

    # 30天数据，累计金额，课程金额，周边商品金额
    @total_price_array = Array.new();
    @total_price_lesson_array = Array.new();
    @total_price_peripheral_array = Array.new();

    for day in ((Date.current - 30.day)..Date.current)
      p nowday = day.strftime('%Y-%m-%d');

      orders = company.orders.where("orders.created_at like ?", "%#{day}%");
        # p orders;

        total_price = orders.sum("total_price");
        @total_price += total_price;
        @total_price_array.push(total_price);

        total_price_lesson = orders.where(good_id: good_ids).sum("total_price");
        @total_price_lesson += total_price_lesson;
        @total_price_lesson_array.push(total_price_lesson);

        # 优化总和＝课程＋周边
        # total_price_peripheral = orders.where.not(good_id: good_ids).sum("total_price");
        total_price_peripheral = total_price - total_price_lesson;
        @total_price_peripheral += total_price_peripheral;
        @total_price_peripheral_array.push(total_price_peripheral);
        
        # p "查询花费时间：#{(Time.now - start)*1000} ms";
    end
    p "累计金额:#{@total_price_array}";
    p "课程累计金额:#{@total_price_lesson_array}";
    p "周边累计金额:#{@total_price_peripheral_array}";
    p "日期周期"
    p @past_month_array;
    p "累积营业额(元)";
    p @total_price;
    p "课程商品金额"
    p @total_price_lesson;
    p "周边商品金额"
    p @total_price_peripheral;



    ################################商品排行榜################################

    # 本月商品数据统计，金额，销售数量排行前十
    today = Time.new().strftime("%Y-%m");
    p "当前日期#{today},本月商品数据统计，金额，销售数量排行前十";

    # 商品排行榜数据查询
    # 销量排行
    results_good_price_orders = company.orders.select("orders.good_id, sum(orders.total_price) as total_price")
                                  .where("orders.created_at like '%#{today}%' ")
                                  .group("orders.good_id")
                                  .order("sum(orders.total_price) asc")
                                  .limit(10);
    
    results_good_amount_orders = company.orders.select("orders.good_id, sum(orders.amount) as amount")
                                  .where("orders.created_at like '%#{today}%' ")
                                  .group("orders.good_id")
                                  .order("sum(orders.amount) asc")
                                  .limit(10);


    @tmp_total_price_all = Array.new(10, 0);#排行榜前十商品金额
    @tmp_total_price_all_name = Array.new(10, "未知");#排行榜前十商品名称

    @tmp_total_amount_all = Array.new(10, 0);#排行榜前十商品数量
    @tmp_total_amount_all_name = Array.new(10, "未知");#排行榜前十商品名称

    for good_price in results_good_price_orders
      # p "价格：",good_price
      @tmp_total_price_all.push(good_price.total_price);
      @tmp_total_price_all_name.push(Good.find_by_id(good_price.good_id).name );
    end

    for good_amount in results_good_amount_orders
      # p "数量：",good_amount
      @tmp_total_amount_all.push(good_amount.amount);
      @tmp_total_amount_all_name.push(Good.find_by_id(good_amount.good_id).name );
    end

    p @tmp_total_price_all = @tmp_total_price_all[-10,10];
    p @tmp_total_price_all_name = @tmp_total_price_all_name[-10,10];

    p @tmp_total_amount_all = @tmp_total_amount_all[-10,10];
    p @tmp_total_amount_all_name = @tmp_total_amount_all_name[-10,10];
    
  end

  def change_commodity

    p "商品分店数据"
    p params[:studio_id]

    p company = current_company;
    p @studios = company.studios;
    studiosIDS = nil;

    if params[:studio_id] ==  "all"
      studiosIDS = company.studios.ids;      
    else
      studiosIDS = params[:studio_id];      
    end

    start = Time.now;

    ################################30天之前总计################################
    # 累积营业额(元)
    @total_price = 0;
    # 课程商品金额
    good_ids = Good.where(good_type: "课程商品").ids;
    @total_price_lesson = 0;
    # 周边商品金额
    @total_price_peripheral = 0;

    # 30天数据，累计金额，课程金额，周边商品金额
    @total_price_array = Array.new();
    @total_price_lesson_array = Array.new();
    @total_price_peripheral_array = Array.new();

    for day in ((Date.current - 30.day)..Date.current)
      p nowday = day.strftime('%Y-%m-%d');

      if params[:studio_id] ==  "all"
        orders = company.orders.where("orders.created_at like ?", "%#{day}%");
      else
        orders = company.orders.where("orders.created_at like ?", "%#{day}%").where(studio_id: params[:studio_id]);
      end
      
        # p orders;
        total_price = orders.sum("total_price");
        @total_price += total_price;
        @total_price_array.push(total_price);

        total_price_lesson = orders.where(good_id: good_ids).sum("total_price");
        @total_price_lesson += total_price_lesson;
        @total_price_lesson_array.push(total_price_lesson);

        # 优化总和＝课程＋周边
        # total_price_peripheral = orders.where.not(good_id: good_ids).sum("total_price");
        total_price_peripheral = total_price - total_price_lesson;
        @total_price_peripheral += total_price_peripheral;
        @total_price_peripheral_array.push(total_price_peripheral);
        
        # p "查询花费时间：#{(Time.now - start)*1000} ms";
    end
    p "累计金额:#{@total_price_array}";
    p "课程累计金额:#{@total_price_lesson_array}";
    p "周边累计金额:#{@total_price_peripheral_array}";
    p "日期周期"
    p @past_month_array;
    p "累积营业额(元)";
    p @total_price;
    p "课程商品金额"
    p @total_price_lesson;
    p "周边商品金额"
    p @total_price_peripheral;



    ################################商品排行榜################################

    # 本月商品数据统计，金额，销售数量排行前十
    today = Time.new().strftime("%Y-%m");
    p "当前日期#{today},本月商品数据统计，金额，销售数量排行前十";

    # 商品排行榜数据查询
    # 销量排行
    results_good_price_orders = company.orders.select("orders.good_id, sum(orders.total_price) as total_price")
                                  .where("orders.created_at like '%#{today}%' ")
                                  .where(studio_id: studiosIDS)
                                  .group("orders.good_id")
                                  .order("sum(orders.total_price) asc")
                                  .limit(10);
    
    results_good_amount_orders = company.orders.select("orders.good_id, sum(orders.amount) as amount")
                                  .where("orders.created_at like '%#{today}%' ")
                                  .where(studio_id: studiosIDS)
                                  .group("orders.good_id")
                                  .order("sum(orders.amount) asc")
                                  .limit(10);


    @tmp_total_price_all = Array.new(10, 0);#排行榜前十商品金额
    @tmp_total_price_all_name = Array.new(10, "未知");#排行榜前十商品名称

    @tmp_total_amount_all = Array.new(10, 0);#排行榜前十商品数量
    @tmp_total_amount_all_name = Array.new(10, "未知");#排行榜前十商品名称

    for good_price in results_good_price_orders
      # p "价格：",good_price
      @tmp_total_price_all.push(good_price.total_price);
      @tmp_total_price_all_name.push(Good.find_by_id(good_price.good_id).name );
    end

    for good_amount in results_good_amount_orders
      # p "数量：",good_amount
      @tmp_total_amount_all.push(good_amount.amount);
      @tmp_total_amount_all_name.push(Good.find_by_id(good_amount.good_id).name );
    end

    p @tmp_total_price_all = @tmp_total_price_all[-10,10];
    p @tmp_total_price_all_name = @tmp_total_price_all_name[-10,10];

    p @tmp_total_amount_all = @tmp_total_amount_all[-10,10];
    p @tmp_total_amount_all_name = @tmp_total_amount_all_name[-10,10];
    
  end

  #招生数据
  def recruit

    @company = current_company
    @studio = params[:studio_id].present? ? Studio.find_by_id(params[:studio_id]) : nil

    #=======最近30天的总计数据=======#
    @total_result = StatisticalDatum::RecruitTotalService.call(@company,@studio)

    #市场专员排行和市场回访数据统计
    @market_result = StatisticalDatum::RecruitMarketService.call(@company,@studio)

    #学员转化比例
    @transf_scale = StatisticalDatum::RecruitTransformStudentScaleService.call(@company,@studio)

    #学员年龄比例
    @potential_student_age_scale = StatisticalDatum::RecruitPotentialStudentAgeScaleService.call(@company,@studio)

    #学员未转化的年龄比例
    @untransf_potential_student_age_scale = StatisticalDatum::RecruitPotentialStudentAgeScaleService.call(@company,@studio,"未转化")

    #学员转化的年龄比例
    @transf_potential_student_age_scale = StatisticalDatum::RecruitPotentialStudentAgeScaleService.call(@company,@studio,"已转化")

    #学员来源比例
    @potential_student_source_scale = StatisticalDatum::RecruitPotentialStudentSourceScaleService.call(@company,@studio)


    #学员性别比例
    @potential_student_sex_scale = StatisticalDatum::RecruitPotentialStudentSexScaleService.call(@company,@studio)

  end

  #服务数据
  def service

    @company = current_company
    @studio = params[:studio_id].present? ? Studio.find_by_id(params[:studio_id]) : nil
    #一个月内的销售额
    @service_total_info = StatisticalDatum::ServiceTotalService.call(@company,@studio)

    #服务顾问排行
    @advisor_order_info = StatisticalDatum::ServiceAdvisorService.call(@company,@studio)
    
  end

  #财务统计,kevin
  def finance

    # flyDragon
    @company = current_company
    #财务总计数据
    @finance_total_info = StatisticalDatum::FinanceTotalService.call(@company,nil)
    # 收入类型比例
    @income_type_scale = StatisticalDatum::FinanceIncomeTypeService.call(@company,nil)
    # 支出类型比例
    @expenditure_type_scale = StatisticalDatum::FinanceExpenditureTypeService.call(@company)
  end

  
  #人资数据
  def resource

    @company = current_company
    @studio = params[:studio_id].present? ? Studio.find_by_id(params[:studio_id]) : nil

    @resource = StatisticalDatum::ResourceService.call(@company,@studio)
  end

  private

  def month_begin_at
    @month_begin_at = Date.new(Date.current.year, Date.current.month)
  end


  def authorize_finance
    authorize Finance,:data?
  end

  def authorize_teacher
    authorize Teacher,:data?
  end

  def authorize_curriculum
    authorize CourseInfo,:data?
  end

end
